from datetime import datetime
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import Products, Tasks
import csv
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse, Http404
from django.contrib.auth import authenticate, logout, login, update_session_auth_hash
from django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm
from django.contrib import messages
from django.contrib.auth.views import LoginView, LogoutView, PasswordChangeView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from django_filters.views import FilterView
from django.urls import reverse, reverse_lazy
from .filters import ProductsFilter
from .forms import ChartSellerForm
import json
# Create your views here.


class ProductsListView(LoginRequiredMixin, ListView):
    model = Products
    login_url = "/v1/login/"
    template_name = 'datapanel/products_list.html'
    context_object_name = 'products'
    paginate_by = 10


class ProductsDetailView(LoginRequiredMixin, DetailView):
    model = Products
    login_url = "/v1/login/"
    template_name = 'datapanel/products_detail.html'
    context_object_name = 'product'


class ProductsFilterView(LoginRequiredMixin, FilterView):
    model = Products
    login_url = "/v1/login/"
    filterset_class = ProductsFilter
    template_name = 'datapanel/products_filter.html'
    paginate_by = 10

    def get_queryset(self):
        queryset = super().get_queryset()
        # Apply any additional filtering or sorting here
        return queryset


def signin(request):
    if request.method == "POST":
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                messages.info(request, "You are now logged in as " + username)
                return redirect("datapanel:products_filter")

            else:
                messages.error(request, "用户名或密码不正确")

        else:
            messages.error(request, "用户名或密码不正确")
    else:
        form = AuthenticationForm()

    return render(request,
                  "datapanel/login.html",
                  {"form": form})


def signout(request):
    logout(request)
    return render(request, "datapanel/logout.html")


def password_change(request):
    if request.method == 'POST':
        form = PasswordChangeForm(user=request.user, data=request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)  # Important!
            messages.success(request, 'Password successfully changed.')
            # so that user does not get logged out, not working as of now.
            return redirect('datapanel:login')
        else:
            messages.error(request, "用户名或密码不正确")
            return redirect('datapanel:password_change_view')
    else:
        form = PasswordChangeForm(user=request.user)
        return render(request, 'datapanel/password_change.html', {'form': form, })


@login_required(login_url='/v1/login/')
def tocsv(request):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="products.csv"'
    writer = csv.writer(response)
    writer.writerow(("id", "name", "short_name", "currency", "price", "brand", "seller", "reviews", "reviews_count", "bought_last_month", "seller_rank",
                    "conn_tech", "connector_type", "ports", "compatiable_phones", "compatible_devices", "voltage", "wattage", "fast_charge", "asin", "create_time"))
    products = Products.objects.all().values_list("id", "name", "short_name", "currency", "price", "brand", "seller", "reviews", "reviews_count", "bought_last_month",
                                                  "seller_rank", "conn_tech", "connector_type", "ports", "compatiable_phones", "compatible_devices", "voltage", "wattage", "fast_charge", "asin", "create_time")
    for product in products:
        writer.writerow(product)
    return response


@login_required(login_url='/v1/login/')
def products_graph(request):
    return render(request, 'datapanel/products_graph.html')


@login_required(login_url='/v1/login/')
def chart_seller(request):
    qs_datalist = []
    qs_date = ""
    if request.method == "POST":
        form = ChartSellerForm(request.POST)
        if form.is_valid():
            # get data from post and prepqre queryset for chart
            for x in form.category_list:
                if request.POST['category'] == x[0]:
                    p_cat = x[1]
                    break
            else:
                p_cat = form.category_list[0][1]
            for x in form.date_list:
                if request.POST['date'] == x[0].strip():
                    p_d = x[1]
                    break
            else:
                p_d = form.date_list[0][1]
            p_date = datetime(*map(int, p_d.split('-'))).date()
            p_sale = request.POST['low_sale']
            p_reviews = request.POST['low_reviews']
            print("received data from POST: ",
                  p_cat, p_date, p_sale, p_reviews)
    else:
        # initiate form with default data
        form = ChartSellerForm(
            initial={'category': '1', 'date': '0', 'low_sale': '120', 'low_reviews': '1000'})
        p_cat = form.category_list[0][1]
        p_date = datetime(*map(int, form.date_list[0][1].split('-'))).date()
        p_sale = 120
        p_reviews = 1000
        print("initial of form data: ",
              p_cat, p_date, p_sale, p_reviews)

    # prepare extra data for chart
    qs = Products.objects.all().order_by("-create_time")
    qs = qs.filter(create_time__contains=p_date).order_by("short_name")
    qs = qs.filter(short_name__icontains=p_cat).order_by(
        "-bought_last_month", "-reviews")
    qs = qs.filter(bought_last_month__gt=p_sale)
    qs = qs.filter(reviews_count__gt=p_reviews)

    print("Found rows: ", len(qs))
    qs_datalist = qs.values(
        "seller", "short_name", "asin", "bought_last_month", "reviews")
    qs_datalist = [x for x in qs_datalist]
    if len(qs_datalist) > 10:
        qs_datalist = qs_datalist[:10]
    qs_date = p_date.strftime("%Y-%m-%d")
    print("datelist: ", qs_datalist)

    return render(request, "datapanel/products_chart_seller.html",   {'form': form, 'qs_datalist': qs_datalist, 'qs_date': qs_date})
